package com.db.data;

import java.util.Locale;

public class Price implements Comparable<Price> {
	
	public static final int countDigitsAfterDecimal = 3;
	
	public static final float accuracy;
	
	static {
		float f = 1;
		for (int i = 0; i < countDigitsAfterDecimal; i++) {
			f /= 10;
		}
		accuracy = f;
	}
	
	private float value;
	
	public float getValue() {
		return value;
	}
	
	public Price() {
		this.value = Float.NaN;
	}
	
	public Price(float value) {
		this.value = value; 
	}
	
	public Price(String value) throws NumberFormatException {
		this.value = Float.parseFloat(value);
	}
	
	public boolean isMarket() {
		return Float.isNaN(value);
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + Float.floatToIntBits(value);
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Price other = (Price) obj;
		if (Math.abs(value - other.value) > accuracy)
			return false;
		return true;
	}

	@Override
	public String toString() {
		if (isMarket()) {
			return "market";
		} else {
			return String.format(Locale.UK, "%." + countDigitsAfterDecimal + "f", value);
		}
	}

	@Override
	public int compareTo(Price other) {
		if (Math.abs(value - other.value) <= accuracy) {
			return 0;
		} else {
			return Float.compare(value, other.value);
		}
	}
}
